package com.zzf.concurrent.example.design.pattern.thread.local;

import lombok.extern.slf4j.Slf4j;

/**
 * @author GaoFeng2017
 * @date 2019/9/8 11:10
 */
@Slf4j
public class ThreadLocalExample {

    private final static ThreadLocal<String> threadLocal = new ThreadLocal<String>() {
        @Override
        protected String initialValue() {
            return "defaultValue";
        }
    };

    /*private final static SimpleThreadLocal<String> threadLocal = new SimpleThreadLocal<String>() {
        @Override
        protected String initialValue() {
            return "defaultValue";
        }
    };*/

    public static void main(String[] args) {
        // singleThreadExample();
        complexThreadExample();
    }

    private static void singleThreadExample() {
        threadLocal.set("1997");
        log.info("{} -> get thread local data, {}",Thread.currentThread().getName(),threadLocal.get());
    }

    private static void complexThreadExample() {

        Thread t1 = new Thread(() -> {
            threadLocal.set(Thread.currentThread().getName());
            log.info("{} -> get thread local data, {}", Thread.currentThread().getName(),
                    threadLocal.get());
        });

        Thread t2 = new Thread(() -> {
            threadLocal.set(Thread.currentThread().getName());
            log.info("{} -> get thread local data, {}", Thread.currentThread().getName(),
                    threadLocal.get());
        });

        t1.start();
        t2.start();

        // threadLocal.set(Thread.currentThread().getName());
        log.info("{} -> get thread local data, {}", Thread.currentThread().getName(),
                threadLocal.get());
    }
}
